package com.example.udp.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.Charset;

@Slf4j
@Component
public class UDPProcess implements Runnable {
    private Integer port = 550;
    private Integer maxUdpDataSize = 1024;
    private DatagramSocket socket;

    @Override
    public void run() {
        try {
            log.info("========当前启动线程：{}=========", Thread.currentThread().getName());
            this.socket = new DatagramSocket(port);
            log.info("=========UDP连接成功，占用端口:{}=========", socket.getLocalPort());
        } catch (SocketException e) {
            e.printStackTrace();
            log.error("=========UDP连接失败=========");
        }
        log.info("=========创建数据包，用于接收客户端数据=========");
        while (true) {
            byte[] buffer = new byte[maxUdpDataSize];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            log.info("=========等待接收UDP数据包=========");
            try {
                socket.receive(packet);
                String ip = packet.getAddress().getHostAddress();
                String msg = new String(packet.getData(), 0, packet.getLength(), Charset.defaultCharset());
                // System.out.println(ip + "---接收到发送过来的数据是：" + msg);
                log.info("{}: 接收到的数据是 {}", ip, msg);
            } catch (IOException e) {
                log.info("=========接收UDP数据包失败！=========");
                e.printStackTrace();
            }
        }
    }
}
